package com.bb.blog.code.collection;


import java.util.AbstractList;
import java.util.Arrays;

public class SomeArrayList<E> extends AbstractList<E> {
    private static final int DEFAULT_CAPACITY = 10;

    transient Object[] elementData;
    private int size;


    public SomeArrayList(int initialCapacity) {
        if (initialCapacity <= 0) {
            initialCapacity = DEFAULT_CAPACITY;
        }
        this.elementData = new Object[initialCapacity];
    }

    public static void main(String[] args) {
        SomeArrayList<Integer> list = new SomeArrayList<>(4);
        for (int i = 0; i < 10; i++) {
            list.add(i);

        }
        list.add(4, 20);
        list.remove(3);
        System.out.println(list);
    }

    @Override
    public E get(int index) {
        rangeCheck(index);
        return elementData(index);
    }

    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);
        elementData[size++] = e;
        return true;

    }

    @Override
    public void add(int index, E element) {
        ensureCapacityInternal(size + 1);
        int numMoved = size - index;
        System.arraycopy(elementData, index, elementData, index + 1, numMoved);
        elementData[index] = element;
        size ++;
    }

    @Override
    public E remove(int index) {
        E oldValue = elementData(index);
        modCount++;
        int numMoved = size - index;
        System.arraycopy(elementData, index + 1, elementData, index, numMoved);
        elementData[--size] = null;
        return oldValue;

    }

    private void ensureCapacityInternal(int i) {
        modCount++;
        if (i - elementData.length > 0) {
            grow();
        }
    }

    private void grow() {
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);

        if (newCapacity - Integer.MAX_VALUE + 8 > 0)
            newCapacity = Integer.MAX_VALUE;
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) this.elementData[index];
    }
}
